<?php

use Wgx\Admin\Com\Crud\Crud;
use Wgx\Admin\Entity\AdminToMenuEntity;

echo 'var _page_data_ = {};' . "\n";

echo "_page_data_['rightEnum'] = " . json_encode(array(
        'RightNone' => AdminToMenuEntity::RightNone,
        'RightRead' => AdminToMenuEntity::RightRead,
        'RightCreate' => AdminToMenuEntity::RightCreate,
        'RightUpdate' => AdminToMenuEntity::RightUpdate,
        'RightDelete' => AdminToMenuEntity::RightDelete,
        'RightAll' => AdminToMenuEntity::RightAll,
    ), JSON_UNESCAPED_UNICODE) . ";\n";
echo "_page_data_['rightMap'] = " . json_encode(AdminToMenuEntity::$rightMap, JSON_UNESCAPED_UNICODE) . ";\n";

/** @var Crud $crud */
$crud = empty($this->data['crud']) ? null : $this->data['crud'];
if (empty($crud)) {
    throw new \InvalidArgumentException('请传递crud');
}
$origRightsMap = array();
$origRights = $crud->getField('rights')->getEpInputWidget()->getOrigValue();
if ($origRights && is_array($origRights)) {
    foreach ($origRights as $right) {
        $origRightsMap[intval($right)] = 1;
    }
}
echo "_page_data_['origRightsMap'] = " . json_encode($origRightsMap, JSON_UNESCAPED_UNICODE) . ";\n";

echo "_page_data_['menuMap'] = {};\n";

?>


jQuery(function ($) {
  $('#page-main-form .form_line.field_menuId .selectonline select').change(function (e) {
    var menuId = $(this).val();
    menuId = menuId && parseInt(menuId) || 0;
    if (!menuId) {
      $('#page-main-form .form_line.field_rights .checkboxgroup').html('');
      return;
    }
    var rights = _page_data_.menuMap
      && _page_data_.menuMap[menuId]
      && _page_data_.menuMap[menuId].rights
      && parseInt(_page_data_.menuMap[menuId].rights)
      || 0;
    if (rights < 1) {
      $('#page-main-form .form_line.field_rights .checkboxgroup').html('');
      return;
    }
    // 使用 rights 计算出 map
    var map = {}, rightMap = _page_data_.rightMap, r;
    if (rightMap) {
      var RightNone = _page_data_.rightEnum && _page_data_.rightEnum.RightNone && parseInt(_page_data_.rightEnum.RightNone) || 0;
      var RightAll = _page_data_.rightEnum && _page_data_.rightEnum.RightAll && parseInt(_page_data_.rightEnum.RightAll) || 0;
      for (r in rightMap) {
        r = r && parseInt(r) || 0;
        if (r == RightNone || r == RightAll) {
          continue;
        }
        if ((rights & r) > 0) {
          map[r] = rightMap[r];
        }
      }
    }
    if ($.isEmptyObject(map)) {
      $('#page-main-form .form_line.field_rights .checkboxgroup').html('');
      return;
    }
    var origRightsMap = _page_data_.origRightsMap || {};
    var html = '';
    for (r in map) {
      html += '<label><input type="checkbox" name="' + r + '" value="' + r + '"'
        + (origRightsMap[r] ? ' checked' : '')
        + ' /><span class="checkbox-label">' + map[r] + '</span></label>';
    }
    $('#page-main-form .form_line.field_rights .checkboxgroup').html(html);
  });
});